package org.example.slave.util;

import io.netty.buffer.ByteBuf;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import org.example.slave.channel.MyChannel;
import org.example.slave.packet.*;

import java.util.Objects;

/**
 * @author dingrui
 * @since 2022/2/15
 * @description
 */
@UtilityClass
public class MysqlCodecUtil {

    // 读取4字节 header中body长度属性 seq_no属性
    @Deprecated
    public HeaderPacket decodeHeaderPacket(ByteBuf byteBuf) {
        HeaderPacket ret = new HeaderPacket();
        byte[] header = new byte[4];
        byteBuf.readBytes(header);
        ret.fromBytes(header);
        return ret;
    }

    @SneakyThrows
    public HeaderPacket readHeader(MyChannel ch, int headerLen) {
        return new HeaderPacket(ch.read(headerLen));
    }

    @SneakyThrows
    public HeaderPacket readHeader(MyChannel ch, int headerLen, long timeout) {
        return new HeaderPacket(ch.read(headerLen, timeout));
    }

    @SneakyThrows
    public byte[] readBytes(MyChannel ch, int len, long timeout) {
        return ch.read(len, timeout);
    }

    public BasePacket readBasePacket(MyChannel ch, int headerLen, long timeout) {
        HeaderPacket headerPacket = readHeader(ch, headerLen, timeout);
        byte[] body = readBytes(ch, headerPacket.getPacketBodyLength(), timeout);
        return new BasePacket(headerPacket, body);
    }

    public byte[] createBodyArrByHeader(ByteBuf byteBuf, HeaderPacket header) {
        assert Objects.nonNull(header);
        int packetBodyLength = header.getPacketBodyLength();
        byte[] body = new byte[packetBodyLength];
        byteBuf.readBytes(body);
        return body;
    }

    public byte[] createBodyArr(ByteBuf byteBuf) {
        HeaderPacket headerPacket = decodeHeaderPacket(byteBuf);
        return createBodyArrByHeader(byteBuf, headerPacket);
    }

    @Deprecated
    public BasePacket decodeBasePacket(ByteBuf byteBuf) {
        BasePacket basePacket = new BasePacket();
        HeaderPacket headerPacket = decodeHeaderPacket(byteBuf);
        byte[] body = createBodyArr(byteBuf);
        basePacket.setHeaderPacket(headerPacket);
        basePacket.setBody(body);
        return basePacket;
    }

    public ErrPacket createErrPacket(byte[] body) {
        return new ErrPacket(body);
    }

    public AuthSwitchRequestMoreData createAuthSwitchRequestMoreDate(byte[] body) {
        AuthSwitchRequestMoreData packet = new AuthSwitchRequestMoreData();
        packet.fromBytes(body);
        return packet;
    }

    public AuthSwitchRequestPacket createAuthSwitchRequestPacket(byte[] body) {
        AuthSwitchRequestPacket packet = new AuthSwitchRequestPacket();
        packet.fromBytes(body);
        return packet;
    }
}
